from models import Model
import time


class Todo(Model):
    # @classmethod
    # def new(cls, form, user_id=-1):
    #     """
    #     创建并保存一个 todo 并且返回它
    #     Todo.new({'task': '吃饭'})
    #     :param form: 一个字典 包含了 todo 的数据
    #     :return: 创建的 todo 实例
    #     """
    #     # 下面一行相当于 t = Todo(form)
    #     t = cls(form, user_id)
    #     t.save()
    #     return t

    # def ct(self):
    #     format = '%H:%M:%S'
    #     value = time.localtime(self.created_time)
    #     dt = time.strftime(format, value)
    #     return dt

    def __init__(self, form):
        self.id = None
        self.task = form.get('title', '')
        self.completed = False
        # 添加创建和修改时间
        self.ct = int(time.time())
        self.ut = self.ct

    # @classmethod
    # def find(cls, id):
    #     return cls.find_by(id=id)

    @classmethod
    def update(cls, id, form):
        t = cls.find(id)
        valid_names = {
            'title',
            'completed'
        }
        for key in form:
            if key in valid_names:
                setattr(t, key, form[key])
        t.ut = int(time.time())
        t.save()
        return t

    @classmethod
    def complete(cls, id, completed=True):
        """
        用法很方便
        Todo.complete(1)
        Todo.complete(2, False)
        """
        t = cls.find(id)
        t.completed = completed
        t.save()
        return t
